package com.novel.crawl.common.dao.impl;

import com.novel.common.dao.impl.BaseDaoImpl;
import com.novel.crawl.common.dao.ChapterDao;
import com.novel.crawl.common.entity.Chapter;
import org.bson.types.ObjectId;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @author zhilong.deng@hand-china.com
 * @date 2018/10/24
 * @version 1.0
 */
@Repository
public class ChapterDaoImpl extends BaseDaoImpl<Chapter> implements ChapterDao {

    @Override
    public Chapter findByUrl(String url) {
        Query query = query(Criteria.where(Chapter.URL_KEY).is(url));
        return findOne(query);
    }

    @Override
    public List<Chapter> findByUrls(List<String> urls) {
        Query query = query(Criteria.where(Chapter.URL_KEY).in(urls));
        return find(query);
    }

    @Override
    public Page<Chapter> pageByBookId(String bookId, Pageable pageable) {
        Criteria criteria = Criteria.where(Chapter.BOOK_ID_KEY).is(bookId);
        return super.page(criteria, pageable);
    }

    @Override
    public List<Chapter> findByBookId(String bookId) {
        Criteria criteria = Criteria.where(Chapter.BOOK_ID_KEY).is(bookId);
        return find(query(criteria));
    }

    @Override
    public Chapter findNextByBookIdAndChapterId(String bookId, String currentChapterId) {
        // 章节升序排列后，取大于本章节id的第一个
        Criteria criteria = Criteria.where(Chapter.BOOK_ID_KEY).is(bookId)
                .and(Chapter.ID_KEY).gt(new ObjectId(currentChapterId));
        Query query = Query.query(criteria)
                .with(new Sort(new Sort.Order(Sort.Direction.ASC, Chapter.SORTED_VALUE_KEY)))
                .limit(1);
        return findOne(query);
    }

    @Override
    public Chapter findPrevByBookIdAndChapterId(String bookId, String currentChapterId) {
        // 章节降序排列后，取小于本章节id的第一个
        Criteria criteria = Criteria.where(Chapter.BOOK_ID_KEY).is(bookId)
                .and(Chapter.ID_KEY).lt(new ObjectId(currentChapterId));
        Query query = Query.query(criteria)
                .with(new Sort(new Sort.Order(Sort.Direction.DESC, Chapter.SORTED_VALUE_KEY)))
                .limit(1);
        return findOne(query);
    }

}
